import { FC, useState, useEffect } from 'react';

import {
  Space,
  Card,
  Table,
  message,
  Button,
  Pagination,
  Form,
  Input,
  Select,
  Popconfirm,
  Modal,
  DatePicker,
} from 'antd';

import request from 'umi-request';

import { formatDate } from '@/utils/index';

/*
  表格数据接口：http://pudge.wang:3000/api/cities/manage/list， post请求
    - 参数
      - page_size：每页条数，默认10条
      - current_page：当前页数，默认第一页
      - city: 选中城市的nm
      - useCar： 用车模式
      - operating： 运营模式
*/

/*
  城市列表接口: http://pudge.wang:3000/api/cities/list, get请求
    - 不需要参数
*/

/*
  删除接口：http://pudge.wang:3000/api/cities/manage/del， post请求
    - 参数
      - id: 每条数据的_id
*/

/*
  新增接口： http://pudge.wang:3000/api/cities/manage/add， post请求
    - 参数
      - admin: "jj"
      - city: "上海"
      - handleTime: 1647659270229
      - openTime: 1648436868649
      - operating: "1"
      - useCar: "1"
*/

const City: FC = () => {
  // form实例
  const [form] = Form.useForm();
  const [addform] = Form.useForm();
  // 表格数据
  const [dataSource, set_dataSource] = useState([]);
  const [count, set_count] = useState<number>(0);
  // 城市数据
  const [cityList, set_cityList] = useState([]);

  // 搜索的对象
  const [search_obj, set_search_obj] = useState({});

  const [page_size, set_page_size] = useState<number>(10);
  const [current_page, set_current_page] = useState<number>(1);

  const [isModalVisible, set_isModalVisible] = useState<boolean>(false);

  const columns = [
    // id一般在页面是不显示的
    {
      title: '城市ID',
      dataIndex: '_id',
    },
    {
      title: '城市名称',
      dataIndex: 'city',
    },
    {
      title: '用车模式',
      dataIndex: 'useCar',
      render(text: string) {
        return <span>{text === '1' ? '禁停区' : '停车点'}</span>;
      },
    },
    {
      title: '运营模式',
      dataIndex: 'operating',
      render(text: string) {
        return <span>{text === '1' ? '自营' : '加盟'}</span>;
      },
    },
    {
      title: '城市管理员',
      dataIndex: 'admin',
    },
    {
      title: '城市开通时间',
      dataIndex: 'openTime',
      render(text: string) {
        return formatDate(+text);
      },
    },
    {
      title: '操作',
      render(text: string, record: any) {
        return (
          <Space>
            <Button>编辑</Button>
            <Popconfirm
              title="Are you sure to delete this task?"
              onConfirm={() => confirm(record._id)}
              okText="Yes"
              cancelText="No"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const confirm = (id: string) => {
    request
      .post('http://pudge.wang:3000/api/cities/manage/del', {
        data: {
          id: id,
        },
      })
      .then((res) => {
        if (res.status === 0) {
          message.success('删除成功');
          // 删除成功重新请求数据
          getTableData();
        }
      })
      .catch((error) => {
        message.error(error.message);
      });
  };

  // 获取表格数据
  const getTableData = () => {
    request
      .post('http://pudge.wang:3000/api/cities/manage/list', {
        data: {
          page_size: page_size,
          current_page: current_page,
          ...search_obj,
        },
      })
      .then((res) => {
        if (res.status === 0) {
          const result = res.result.map((item: any) => {
            return { ...item, key: item._id };
          });
          set_dataSource(result);
          set_count(res.total);
        }
      })
      .catch((error) => {
        message.error(error.message);
      });
  };

  // 获取城市列表
  const getCityList = () => {
    request
      .get('http://pudge.wang:3000/api/cities/list')
      .then((res) => {
        set_cityList(res.cts);
      })
      .catch((error) => {
        message.error(error.message);
      });
  };

  // 分页的页码和每页条数改变
  const onChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    set_current_page(page);
    set_page_size(pageSize);
  };

  // 搜索
  const search = () => {
    set_current_page(1);
    set_search_obj(form.getFieldsValue());
  };

  // 重置
  const reset = () => {
    form.resetFields();
    set_search_obj({});
  };

  // 打开新增狂
  const add = () => {
    addform.resetFields();
    set_isModalVisible(true);
  };

  // 新增确定
  const handleOk = () => {
    // set_isModalVisible(false);
    // console.log(addform.getFieldsValue());
    addform
      .validateFields()
      .then(() => {
        const addObj = addform.getFieldsValue();

        request
          .post('http://pudge.wang:3000/api/cities/manage/add', {
            data: {
              ...addObj,
              openTime: new Date(addObj.openTime).getTime(),
              handleTime: new Date().getTime(),
            },
          })
          .then((res) => {
            if (res.status === 0) {
              message.success('新增成功');
              set_isModalVisible(false);
              getTableData();
            }
          })
          .catch((error) => {
            message.error(error.message);
          });
      })
      .catch(() => {
        // message.warning('输入不完整');
      });
  };

  // 新增取消
  const handleCancel = () => {
    set_isModalVisible(false);
  };

  useEffect(() => {
    getTableData();
  }, [page_size, current_page, search_obj]);

  useEffect(() => {
    getCityList();
  }, []);

  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      {/* 搜索表单 */}
      <Card>
        <Form form={form} name="horizontal_login" layout="inline">
          <Form.Item name="city" label="城市">
            <Select style={{ width: 120 }} allowClear>
              {cityList.map((item: any) => (
                <Select.Option value={item.nm} key={item.id}>
                  {item.nm}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="useCar" label="用车模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="operating" label="运营模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={search}>
                查询
              </Button>
              <Button onClick={reset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格 */}
      <Card title="城市管理">
        <Button type="primary" style={{ float: 'right' }} onClick={add}>
          新增
        </Button>

        <Table dataSource={dataSource} columns={columns} pagination={false} />

        <Pagination
          showSizeChanger
          onChange={onChange}
          defaultCurrent={1}
          total={count}
          style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}
        />
      </Card>

      {/* 新增框 */}
      <Modal
        title="新增"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 17 }}
          autoComplete="off"
          form={addform}
        >
          <Form.Item
            label="城市"
            name="city"
            rules={[{ required: true, message: '请选择城市!' }]}
          >
            <Select allowClear>
              {cityList.map((item: any) => (
                <Select.Option value={item.nm} key={item.id}>
                  {item.nm}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="用车模式"
            name="useCar"
            rules={[{ required: true, message: '请选择用车模式!' }]}
          >
            <Select allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="运营模式"
            name="operating"
            rules={[{ required: true, message: '请选择运营模式!' }]}
          >
            <Select allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="管理员"
            name="admin"
            rules={[{ required: true, message: '请输入管理员!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="开通时间"
            name="openTime"
            rules={[{ required: true, message: '请选择开通时间!' }]}
          >
            <DatePicker />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
};

export default City;
